package com.school.movie.common.config;

/**
 * @author zhaoren
 * @version 1.0
 * @description shiro配置类
 * @date 2020/8/19 15:15
 **/

import com.school.movie.common.component.JurisdictionRealm;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.LinkedHashMap;
import java.util.Map;


/**
 * 大坑，不要在Configuration中注入需要成为代理对象的对象，否则原来的对象就会变成是普通对象
 * 什么事务管理之类的增强都会失效，因为不是代理对象
 *
 * @author swift
 */
@EnableAspectJAutoProxy()
@Configuration()
public class ShiroConfiguration implements WebMvcConfigurer {


    /**
     * 配置shiro的securityManager
     *
     * @return
     */
    @Bean
    public SecurityManager securityManager(JurisdictionRealm jurisdictionRealm) {
        DefaultSecurityManager securityManager = new DefaultWebSecurityManager(jurisdictionRealm);
        securityManager.setCacheManager(new MemoryConstrainedCacheManager());
        return securityManager;
    }

    /**
     * shiro过滤器,配置url拦截请求等
     *
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean filter = new ShiroFilterFactoryBean();
        filter.setSecurityManager(securityManager);
        filter.setLoginUrl("/mobile/login");
        Map<String, String> filterChainMap = new LinkedHashMap<>(16);
        filterChainMap.put("/**", "anon");
        filterChainMap.put("/mobile/logout", "logout");
        filterChainMap.put("/mobile/**", "authc");
        filter.setFilterChainDefinitionMap(filterChainMap);

        return filter;
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }


}
